package {
	import flash.display.BitmapData;
	import flash.media.Camera;
	import flash.media.Video;
	import flash.utils.ByteArray;
	
	import org.libspark.flartoolkit.core.FLARCode;
	import org.libspark.flartoolkit.core.param.FLARParam;
	import org.libspark.flartoolkit.core.raster.rgb.FLARRgbRaster_BitmapData;
	import org.libspark.flartoolkit.detector.FLARSingleMarkerDetector;
	
	public class PaletaPosition implements Detector{
		[Embed(source="../lib/camera_para.dat", mimeType="application/octet-stream")]
		private var CameraParameters:Class;
		[Embed(source="../lib/square.pat", mimeType="application/octet-stream")]
		private var MarkerPattern:Class;
		private var cameraParameters:FLARParam;
		private var markerPattern:FLARCode;
		private var raster:FLARRgbRaster_BitmapData;
		private var detector:FLARSingleMarkerDetector;
		private var camera:Camera;
		private var video:Video;
		private var snapshot:BitmapData;
		private var lastX:int = 0;
		private var lastY:int = 0;
		private var x:int = 0;
		private var y:int = 0;
		
		public function PaletaPosition() {
			// Camera init
			this.initCamera();
			
			// Flar init
			this.cameraParameters = new FLARParam();
			this.cameraParameters.loadARParam(new CameraParameters() as ByteArray);
			this.markerPattern = new FLARCode(16, 16);
			this.markerPattern.loadARPatt(new MarkerPattern());
			detector = new FLARSingleMarkerDetector(cameraParameters, markerPattern, 80);
		}
		
		public function initCamera():void {
			this.camera = Camera.getCamera();
			this.camera.setMode(640, 480, 60, false);
			this.video = new Video(640, 480);
			this.video.attachCamera(camera);
			this.snapshot = new BitmapData(video.width, video.height, false, 0x0);
		}
		
		public function getVideo():Video {
			return this.video;
		}
		
		public function detect():void {
			snapshot.draw(video);
			raster = new FLARRgbRaster_BitmapData( snapshot );
			if (detector.detectMarkerLite(raster, 80) && detector.getConfidence() > 0.3 ) {
				// Detected!
				this.x = (detector.getSquare().imvertex[0].x + detector.getSquare().imvertex[1].x +
					detector.getSquare().imvertex[2].x + detector.getSquare().imvertex[3].x) / 4;
				this.y = (detector.getSquare().imvertex[0].y + detector.getSquare().imvertex[1].y +
					detector.getSquare().imvertex[2].y + detector.getSquare().imvertex[3].y) / 4;
			}else{
				this.x = this.lastX;
            	this.y = this.lastY;
			}
			this.lastX = x;
			this.lastY = y;
		}
		
		public function getX():Number {			
			return new Number(this.x);
		}
		
		public function getY():Number {
			return new Number(this.y);
		}

	}
}